package bt

import (
	"bytes"
	"sync"
)

type BtSession struct{

	btComplatePeer 	*BtPeerSession
	btActivePeer 	*BtPeerSession

	hashvalue 	string

}

func newBtSession(hash string) *BtSession {

	bt := new(BtSession)

	bt.btComplatePeer 	= newBtPeerSession()
	bt.btActivePeer 	= newBtPeerSession()

	bt.hashvalue = hash
	return bt
}


func (p *BtSession) GetKey() string {
	return p.hashvalue
}

func (p *BtSession) StopPeer(req *Request) {


	p.btComplatePeer.DelPeer(req)
	p.btActivePeer.DelPeer(req)

}
func (p *BtSession) StartPeer(req *Request) {

	p.btActivePeer.SetPeer(req)

}
func (p *BtSession) ComplatePeer(req *Request) {

	p.btActivePeer.DelPeer(req)
	p.btComplatePeer.SetPeer(req)

}

func (p *BtSession) GetPeer(req *Request) [] byte{

	buf := new(bytes.Buffer)

	var waitgroup sync.WaitGroup

	waitgroup.Add(2)

	Compltebuf := new(bytes.Buffer)
	Activebuf := new(bytes.Buffer)

	go func() {
		Compltebuf.Write(p.btComplatePeer.GetPeers(req,req.NumWant/2))
		waitgroup.Done()
	}()

	go func() {
		Activebuf.Write(p.btActivePeer.GetPeers(req,req.NumWant/2))
		waitgroup.Done()
	}()


	waitgroup.Wait()

	buf.Write(Compltebuf.Bytes())
	buf.Write(Activebuf.Bytes())

	return buf.Bytes()
}

func (p *BtSession) ComplatePeersCount() int32 {
	return p.btComplatePeer.GetPeerSize(ComplateString)
}

func (p *BtSession) StartPeersCount() int32 {
	return p.btActivePeer.GetPeerSize(StartString)
}



